using UnityEngine;
using System.Collections;

public class AnimatedGUI : MonoBehaviour 
{
	public static AnimatedGUI Instance;
	
	public bool dontPlayOnStart;
	public bool isPlayOnce;
	bool isPlaying = false;
	
	public string[] assetName;
	
	public float speed;
	
	public int currentFrame;
	
	UISprite myUISprite;
	
	void Awake ()
	{
		Instance = this;
	}
	
	void OnEnable()
	{
		currentFrame = 0;
		isPlaying = false;
		myUISprite = this.GetComponent<UISprite>();
		
		if( PlayerPrefs.GetInt("Audio") == 1 || PlayerPrefs.GetInt("Sound") == 1 )
		{
			AnimateMeTrigger( true );
		}
		else
		{
			AnimateMeTrigger( false );
		}
	}
	
	public void AnimateMeTrigger ( bool animate )
	{

		if ( animate )
		{
			if ( !isPlaying )
				StartCoroutine("AnimateMe");
		}
		else
		{
			isPlaying = false;
			StopCoroutine("AnimateMe");
			myUISprite.spriteName = "0";
		}

	}
	
	IEnumerator AnimateMe()
	{
		isPlaying = true;
		
		Vector3 scale = transform.localScale;
		
		while(this.gameObject.activeSelf)
		{
			myUISprite.spriteName = assetName[currentFrame];
			scale.x = myUISprite.atlas.GetSprite(assetName[currentFrame]).inner.width;
			scale.y = myUISprite.atlas.GetSprite(assetName[currentFrame]).inner.height;
			transform.localScale = scale;
			
			currentFrame++;
			
			if(currentFrame > assetName.Length - 1)
			{
				if(isPlayOnce)
					break;
				
				currentFrame = 0;
			}

			yield return new WaitForSeconds(speed);
		}
	}
}
